function OneTurnRight()
  StartingRotationB = rotationCounts(B)
  repeat
    forward(A, 20)
    forward(B, -15)
  until abs(rotationCounts(B)-StartingRotationB) > 100
end

function OneTurnLeft()
  StartingRotationA = rotationCounts(A)
  repeat
    forward(A, -15)
    forward(B, 20)
  until abs(rotationCounts(A)-StartingRotationA) > 100
end

function MoveAway(SonarDistance)
  StartSonarReading = sonarReading(4)
  OneTurnRight()
  if sonarReading(4) < SonarDistance then
    if sonarReading(4) > StartSonarReading then
      OneTurnRight()
    else
     OneTurnLeft()
     OneTurnLeft()
    end
  else
  end
end

function motion(HowFar, SonarDistance)
  StartingRotationA = rotationCounts(A)
  StartingRotationB = rotationCounts(B)
  forward(A, 50)
  forward(B, 50)
end

function turn(left, right, distance) 
    StartingRotationA = rotationCounts(A)
    StartingRotationB = rotationCounts(B)
    repeat
       forward(A, left)
       forward(B, right)
       if isPressed(ESCAPE) then
           escape = true
           break
       end
    until distance < abs(rotationCounts(A)-StartingRotationA) or escape == true or sawsomething == true

end

function DirectedMotion(SonarDistance, FarToGo)
  if sonarReading(4) < SonarDistance then
     sawsomething = true
  else
     motion(FarToGo, SonarDistance)
  end
  if isPressed(ESCAPE) then
      escape = true
  end
end

function WanderForLight()

  repeat
    resetRotationCount(A)
    resetRotationCount(B)
    distance = nxt.random(300, 1000)

    left = 20
    right = 20
    repeat
        DirectedMotion(25)
        currentlight = activeLightReading(3)

    until rotationCounts(B) > distance or escape == true or currentlight > brightest

    if currentlight > brightest then
        brightest = currentlight
        nxt.sleep(2000)
    end
    ranforturn = nxt.random(2, 1)
    if ranforturn == 1 then 
        right = right * -1
    else
        left = left * -1
    end
    turn(right, left, 100)
  until escape == true
end

function LightFinding()
  escape = false
  brightest = activeLightReading(3)

  repeat 
  WanderForLight()
  if isPressed(ESCAPE) then
      escape = true
  end
  until escape == true

  forward(A, 0)
  forward(B, 0)
end


